package com.lianjinsu.shop.core.helper;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;

import java.util.Objects;

public class SpringContextHelper extends ApplicationObjectSupport {

    private static volatile ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> cls) {
        return applicationContext.getBean(cls);
    }

    private static void initContext(ApplicationContext context) {
        if (Objects.isNull(applicationContext)) {
            synchronized (SpringContextHelper.class) {
                if (Objects.isNull(applicationContext)) {
                    applicationContext = context;
                }
            }
        }
    }

    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        initContext(context);
    }
}
